package com.hbusa.dao.impl;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.Page;
import cn.hutool.db.PageResult;
import cn.hutool.db.sql.Condition;
import cn.hutool.db.sql.Direction;
import cn.hutool.db.sql.Order;
import com.hbusa.dao.NovelsDao;
import com.hbusa.dto.TbChapter;
import com.hbusa.dto.TbNovels;

import java.sql.Date;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Sandwich
 * @version 1.0
 * @date 2021/12/26-0:15
 */



public class NovelsDaoImpl implements NovelsDao {


    //增
    @Override
    public boolean save(TbNovels novels) {
        int insert = 0;
        try {
            insert = Db.use().insert(
                    Entity.create("tb_novels")
                            .set("novel_name",novels.getNovelName())
                            .set("author",novels.getAuthor())
                            .set("last_date",novels.getLastDate())
                            .set("classify_id",novels.getClassifyId())
                            .set("state",novels.getState())
                            .set("picture_id",novels.getPictureId())
                            .set("is_recommend",novels.getIsRecommend())
                            .set("describes",novels.getDescribes())
            );
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return insert > 0;
    }

    //改
    @Override
    public boolean modify(TbNovels novels) throws SQLException {
        int update = Db.use().update(
                Entity.create()
                        .set("novel_name",novels.getNovelName())
                        .set("author",novels.getAuthor())
                        .set("last_date",novels.getLastDate())
                        .set("classify_id",novels.getClassifyId())
                        .set("state",novels.getState())
                        .set("picture_id",novels.getPictureId())
                        .set("is_recommend",novels.getIsRecommend())
                        .set("describes",novels.getDescribes()),
                Entity.create("tb_novels")
                        .set("novel_id",novels.getNovelId())
        );
        return update > 0;
    }

    //删
    @Override
    public boolean removeById(int novelId) {
        int bookId = 0;
        try {
            bookId = Db.use().del(
                    Entity.create("tb_novels")
                            .set("novel_id",novelId)
            );
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return bookId > 0;
    }

    //查询所有小说
    @Override
    public ArrayList<TbNovels> findAll() {

        ArrayList<TbNovels> novels = new ArrayList<>();
        List<Entity> tb_novels = null;
        String s = "";
        try {
            tb_novels = Db.use().findAll("tb_novels");
            for (Entity tb_novel : tb_novels) {
                    TbNovels novels1 = new TbNovels(
                            (int)    tb_novel.get("novel_id"),
                            (String) tb_novel.get("novel_name"),
                            (String) tb_novel.get("author"),
                            (Date) tb_novel.get("last_date"),
                            (String) tb_novel.get("classify_id"),
                            (String) tb_novel.get("state"),
                            (int)    tb_novel.get("picture_id"),
                            (int)    tb_novel.get("is_recommend"),
                            (String) tb_novel.get("describes")
                    );
                    novels.add(novels1);
            }
//            for (ArrayList<Object> objects : novels) {
//                for (Object object : objects) {
//                    s += object + " ";
//                }
//                s += "!";
//            }
        } catch (SQLException e) {
            e.printStackTrace();
        }


        return novels;
    }

    //模糊查询
    @Override
    public ArrayList<TbNovels> findByString(String novelName) {
        ArrayList<TbNovels> novels = new ArrayList<>();
        List<Entity> query = null;
        try {
            query = Db.use().query("SELECT * FROM tb_novels WHERE novel_name LIKE ?", "%"+novelName+"%");
            System.out.println(query);
            for (Entity entity : query) {
                System.out.println(entity);
                TbNovels novels1 = new TbNovels(
                        (int)entity.get("novel_id"),
                        (String)entity.get("novel_name"),
                        (String)entity.get("author"),
                        (Date) entity.get("last_date"),
                        (String)entity.get("classify_id"),
                        (String)entity.get("state"),
                        (int)entity.get("picture_id"),
                        (int)entity.get("is_recommend"),
                        (String) entity.get("describes")
                );
                novels.add(novels1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return novels;
    }

    //通过小说id查询小说
    @Override
    public TbNovels findNovelById(int novelId) throws SQLException {
        List<TbNovels> novel = null;
        novel = Db.use().find(
                Entity.create("tb_novels")                          //哪张表
                        .set("novel_id",novelId),TbNovels.class      //条件以及返回
        );
        return novel != null && novel.size() > 0 ? novel.get(0): null;  //查到小说返回小说类，否则返回空
    }

    /**
     *
     * @param pageindex 当前页
     * @param pagesize  每页显示的条目数
     * @param searchMap 查询的条件
     * @return
     */
    @Override
    public PageResult<Entity> queryByPage(int pageindex, int pagesize, Map<String, Object> searchMap) {
        Entity tb_novels = Entity.create("tb_novels");
        if (searchMap != null && searchMap.size() > 0)
        {
            Set<Map.Entry<String, Object>> entries = searchMap.entrySet();
            for (Map.Entry<String, Object> entry : entries) {
                String key = entry.getKey();
                Object value = entry.getValue();
                tb_novels.set(key, value);
            }
        }

        // 分页查询
        PageResult<Entity> page = null;
        try {
            Page pageEntity = new Page(pageindex, pagesize);
            pageEntity.addOrder(new Order("novel_id", Direction.DESC));
            page = Db.use().page(
                    tb_novels, pageEntity);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return page;
    }


    public ArrayList<TbChapter> queryChapterByNovelId(Long id) {
        ArrayList<TbChapter> tbChapters = new ArrayList<>();
        try {
            List<Entity> all = Db.use().findAll(Entity.create("tb_chapter").set("novel_id", id));
            for (Entity entity : all) {
                TbChapter tbChapter = new TbChapter();
                tbChapter.setChapterId((int) entity.get("chapter_id"));
                tbChapter.setChapterName((String)entity.get("chapter_name"));
                tbChapter.setChapterNum((String)entity.get("chapter_num"));
                tbChapter.setContent((String) entity.get("content"));
                tbChapter.setNovelId((int) entity.get("novel_id"));
                tbChapter.setUpdateTime((Date) entity.get("update_time"));
                tbChapters.add(tbChapter);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return tbChapters;
    }

    /*
* 小说数据库里有的字段

*
*
  private long novelId;             主键不需要操作
  private String novelName;
  private String author;
  private java.sql.Date lastDate;
  private String classifyId;
  private String state;
  private long pictureId;
  private long isRecommend;
* */
    public static void main(String[] args) {
        NovelsDaoImpl novel = new NovelsDaoImpl();
        Date date = new Date(System.currentTimeMillis());

        //添加测试
//        novel.save(new TbNovels(0,
//                "斗破苍穹",
//                "天蚕土豆",
//                date,
//                "1",
//                "已完结",
//                16,
//                1,
//                "《斗破苍穹》讲述了天才少年萧炎在创造了家族空前绝后的修炼纪录后突然成了废人,种种打击接踵而至。就在他即将绝望的时候,一缕灵魂从他手上的戒指里浮现,一扇全新的大门在面前开启,经过艰苦修炼最终成就辉煌的故事。"));
//
        //测试代码
//        List<Entity> tb_novels = null;
//        try {
//            tb_novels = Db.use().findAll("tb_novels");
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }
//        Entity entity = tb_novels.get(0);
//        Set<String> fieldNames = entity.getFieldNames();
//        System.out.println("-------"+fieldNames);
//        for (String fieldName : fieldNames) {
//            System.out.println(fieldName);
//            System.out.println("||||||||||||||" + entity.get(fieldName));
//
//        }
//        System.out.println(entity);
//        System.out.println("tb_novels->" + tb_novels);
//        System.out.println(entity);

//        TbNovels all = novel.findAll();
//        System.out.println(all);

        //查询所有
//        ArrayList<TbNovels> s = novel.findAll();
//
//        for (TbNovels novels : s) {
//            System.out.println(novels);
//        }

        //查询id为2小说
//        try {
//            TbNovels novelById = novel.findNovelById(2);
//            System.out.println(novelById.getAuthor());
//            System.out.println(novelById);
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }

        //测试修改
//        try {
//            novel.modify(new TbNovels(1, "斗罗大陆", "唐家三少", date, "1", "已完结", 11, 1, "唐门外门弟子唐三，因偷学内门绝学为唐门所不容，跳崖明志时却发现没有死，反而以另外一个身份来到了另一个世界，一个属于武魂的世界，名叫斗罗大陆。这里没有魔法，没有斗气，没有武术，却有神奇的武魂。这里的每个人，在自己六岁的时候，都会在武魂殿中令武魂觉醒。\n" +
//                    "\n" +
//                    "武魂有动物，有植物，有器物，武魂可以辅助人们的日常生活。而其中一些特别出色的武魂却可以用来修炼并进行战斗，这个职业，是斗罗大陆上最为强大也是最荣耀的职业“魂师”。\n" +
//                    "\n" +
//                    "小小的唐三在圣魂村开始了他的魂师修炼之路，并萌生了振兴唐门的梦想。当唐门暗器来到斗罗大陆，当唐三武魂觉醒，他能否在这片武魂的世界再铸唐门的辉煌？")); //第一个参数是修改小说的id
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }

        //测试删除
//        novel.removeById(3);

        //测试完成，增删改查函数都已经实现

        //模糊查询测试 测试成功
//        System.out.println(novel.findByString("斗"));

    }

}

